<?php


namespace common\service;

use common\exception\LogicException;
use common\model\EditProjectModel;
use common\model\CosMediaModel;
use support\SingletonTrait;
use support\ErrorCode;
use think\Exception;
use Throwable;

/**
 * 剪辑工程
 */
class EditProjectService
{
    use SingletonTrait;


    /**
     * 处理关联数据
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function handleRelationIds($data)
    {
        $editProjectModel = model(EditProjectModel::class);
        $editProjectModel->setCurrentModuleCode('edit_project');
        $currentModuleLinkRelation = $editProjectModel->parserFilterModuleRelation(true);
        $relationIds = [];
        foreach ($data as $moduleCode => $item) {
            if (empty($currentModuleLinkRelation[$moduleCode]) || $currentModuleLinkRelation[$moduleCode]['module_code'] != 'cos_media') {
                continue;
            }
            $mediaIds = [];
            if (!is_many_dimension_array($item)) {
                continue;
            }
            foreach ($item as $mediaItem) {
                if (empty($mediaItem)) {
                    continue;
                }
                $mediaData = CosMediaService::getInstance()->findAddMedia($mediaItem);
                if (!$mediaData) {
                    throw new LogicException(model(CosMediaModel::class)->getError(), ErrorCode::MEDIA_ADD_FAILURE);
                } else {
                    if (!in_array($mediaData['id'], $mediaIds)) {
                        $mediaIds[] = $mediaData['id'];
                    }
                }
            }
            $relationIds[$moduleCode] = join(',', $mediaIds);
        }
        return $relationIds;
    }

    /**
     * 上传剪辑工程
     * @param $data
     * @return array
     * @throws Throwable
     * @throws Exception
     */
    public function upload($data)
    {
        $editProjectModel = model(EditProjectModel::class);
        $editProjectModel->setCurrentModuleCode('edit_project');
        $editProjectModule = module_by_code('edit_project');
        $editProjectModel->startTrans();
        try {
            $relationIds = $this->handleRelationIds($data);
            // 把水平自定义关联数据回插入主表
            foreach ($relationIds as $field => $relationId) {
                $data['edit_project'][$field] = $relationId;
            }
            $commonService = CommonService::instance("edit_project");
            if (empty($data["edit_project"]["id"])) {
                //新增
                $resData = $commonService->commonCreate(['data' => $data['edit_project']], $editProjectModule);
            } else {
                $resData = $commonService->commonUpdate(['data' => $data['edit_project']], $editProjectModule, false);
            }
            $editProjectModel->commit();
            return $resData;
        } catch (Throwable $e) {
            $editProjectModel->rollback();
            throw $e;
        }
    }

    /**
     * 查询
     * @param $param
     * @return array
     * @throws \Exception
     */
    public function select($param)
    {
        $res = model(EditProjectModel::class)->selectData($param);
        $createdBy = [];
        foreach ($res['rows'] as $row) {
            $createdBy[$row['edit_project']['created_by']] = $row['edit_project']['created_by'];
        }
        $userList = [];
        if (!empty($createdBy)) {
            $userList = UserService::getInstance()->selectLocalUserList(['id' => ['IN', implode(',', $createdBy)]], ['id,name,avatar']);
            $userList = array_column($userList, null, 'id');
        }
        foreach ($res['rows'] as &$row) {
            $row['created_by'] = $userList[$row['edit_project']['created_by']] ?? null;
        }
        return $res;
    }
}